<?php

namespace common\traits;

use common\helpers\WordMatcher;
use yii\helpers\ArrayHelper;

/**
 * Description of Constants
 *
 * @author emhome
 */
trait UnifiedKeyword {

    /**
     * @var string 操作内容类型
     */
    public $keyword;

    /**
     * @var bool 
     */
    public $useLibrary = false;

    /**
     * @var string 操作内容类型
     */
    private $_libs = [];

    /**
     * @var string 操作内容类型
     */
    private $_words = [];

    /**
     * @inheritdoc
     */
    public function rules() {
        $rules = [];
        $method = 'addRules';
        $handler = array($this, $method);
        if ($this->hasMethod($method) && is_callable($handler)) {
            $rules = call_user_func_array($handler, $this);
        }
        return ArrayHelper::merge([
            [['keyword'], 'string'],
            [['keyword'], 'validateKeyword'],
        ], $rules);
    }

    public function validateKeyword($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $keyword = $this->$attribute;
        if (!$keyword) {
            return;
        }
        $tempWords = explode(' ', $keyword);
        if (!empty($tempWords)) {
            $this->_words = array_unique($tempWords);
        }
        if ($this->useLibrary) {
            $matcher = new WordMatcher();
            $matcher->match($keyword, $matched);
            if (!empty($matched)) {
                $this->_libs = array_keys($matched);
            }
        }
    }

    public function getWords() {
        return $this->_words;
    }

    public function getLibs() {
        return $this->_libs;
    }

}
